<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col :span="3">
        <el-date-picker
          style="width: 100%"
          v-model="tableDatas.filters.REPORT_DATE"
          type="date"
          placeholder="选择填报日期"
          format="YYYY/MM/DD"
          value-format="YYYY/MM/DD"
        />
      </el-col>
      <el-col :span="3">
        <el-select
          v-model="tableDatas.filters.P_ID"
          filterable
        >
          <el-option
            v-for="item in tableDatas.filters.P_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <div v-if="item.isDate">
              <el-date-picker
                v-model="dialogDatas.currentData[item.value]"
                :type="item.dateOption ? item.dateOption.type : 'date'"
                :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
                :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
                :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
                :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
                :disabled="item.disable"
              />
            </div>

            <div
              v-else-if="item.isSelect"
              style="width: 100%"
            >
              <el-select
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
                filterable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div
              v-else-if="item.isSwitch"
              style="width: 100%"
            >
              <el-switch
                v-model="dialogDatas.currentData[item.value]"
                inline-prompt
                active-text="启用"
                inactive-text="不启用"
                :active-value="item.trueValue"
                :inactive-value="item.falseValue"
                :disabled="item.disable"
              />
            </div>
            <div
              v-else
              style="width: 100%"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
      max-height="80vh"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :type="column.type"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <div>
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>

        <template
          #default="scope"
          v-if="column.prop =='VALUE'"
        >
          <div>
            <el-input-number
              v-model="scope.row['VALUE']"
              :min="0"
              :step="1"
              step-strictly
            />
          </div>
        </template>

      </el-table-column>
    </el-table>

    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

    <div class="marginTop10">
      <el-button
        type="success"
        @click="buttonClick.submitBtnClick"
      >提交</el-button>
      <el-button
        type="warning"
        @click="buttonClick.clearBtnClick"
      >清空</el-button>
    </div>
  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import { dayjs } from 'element-plus';
import myAxios193 from '@/myAxios/myAxios193';

export default {
  name: 'ReportView',
  setup () {
    let loading = ref(false);

    let addBtnClick = function () {
      showFormDialog();
    };
    let submitBtnClick = function () {
      loading.value = true;

      let REPORT_ID = tableDatas.oritableData[0]['REPORT_ID'];
      if (!REPORT_ID) {
        REPORT_ID = v4();
      }
      let DATE = tableDatas.filters.REPORT_DATE;
      let TIME = dayjs().format('YYYY/MM/DD HH:mm:ss');
      let P_ID = tableDatas.filters.P_ID;
      let WORK_TIME = 0;
      // 总金额(司机)
      let ADJUST_TIME = 0;

      let itemParamArr = [];
      tableDatas.oritableData.forEach(item => {
        let row = item;
        let REPORT_ITEM_ID = row.REPORT_ITEM_ID ? row.REPORT_ITEM_ID : v4();
        //计算总金额(司机)
        if (row.GX_TYPE == '司机') {
          ADJUST_TIME += row.VALUE * row.STD_TIME;
        }
        //计算总工时
        else {
          WORK_TIME += row.VALUE * row.STD_TIME;
        }

        let params = `${REPORT_ITEM_ID}`
          + `\t${REPORT_ID}`
          + `\t${row.GX_ID}`
          + `\t${row.VALUE}`
          + `\t${row.REMARK}`;
        itemParamArr.push(params);
        // let requestName = `陈帅廷添加或修改配送中心报工子表`;
      });
      // ADJUST_TIME = WORK_TIME;
      let mainParam = `${REPORT_ID}`
        + `\t${DATE}`
        + `\t${TIME}`
        + `\t${P_ID}`
        + `\t${WORK_TIME}`
        + `\t${ADJUST_TIME}`;
      let mainParamArr = [mainParam];
      let dataContent = {
        requestNames: ['陈帅廷添加或修改配送中心报工主表', '陈帅廷添加或修改配送中心报工子表'],
        requestParamsArrs: [mainParamArr, itemParamArr],
        requestFactorys: ["9900", "9900"],
      };

      myAxios193.post('users/postDiffMutipleRequests', JSON.stringify(dataContent)).then(async res => {
        if (res.returnData.message.includes('全部成功')) {
          loading.value = false;

          ElMessage({
            showClose: true,
            type: 'success',
            message: '提交成功!',
          });
          tableDatas.filters.P_ID = '';

        }
        else {
          loading.value = false;
          showWarning('更新失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('更新失败err!' + err);
      });
    };
    let clearBtnClick = function () {
      tableDatas.oritableData.forEach(item => {
        item.VALUE = 0;
      });
    };

    let buttonClick = {
      addBtnClick,
      submitBtnClick,
      clearBtnClick,
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        {
          "value": "REPORT_TIME",
          "label": "填报时间",
          "isDate": false
        },
        {
          "value": "P_ID",
          "label": "填报人ID",
          "isDate": false
        },
        {
          "value": "REPORT_ID",
          "label": "REPORT_ID",
          "isDate": false
        },
        {
          "value": "REPORT_DATE",
          "label": "填报日期",
          "isDate": false
        },
        {
          "value": "EMP_DEPARTMENT",
          "label": "部门",
          "isDate": false,
          "disable": false,
          "isSelect": true,
          "selectOptions": [
            {
              "value": "value_1",
              "label": "label_1"
            },
            {
              "value": "value_2",
              "label": "label_2"
            }
          ]
        },
        {
          "value": "DATE_TIME",
          "label": "精确到秒的时间(示例,可删除)",
          "isDate": true,
          "dateOption": {
            "type": "datetime",
            "format": "YYYY/MM/DD HH:mm:ss",
            "dateFormat": "YYYY/MM/DD",
            "timeFormat": "HH:mm:ss",
            "valueFormat": "YYYY/MM/DD HH:mm:ss"
          }
        }
      ],
      confirmBtnClick: function () {
        loading.value = true;
        let row = dialogDatas.currentData;
        let REPORT_ID = row.REPORT_ID ? row.REPORT_ID : v4();

        let params = `${REPORT_TIME}`
          + `\t${dialogDatas.currentData.P_ID}`
          + `\t${dialogDatas.currentData.REPORT_ID}`
          + `\t${dialogDatas.currentData.REPORT_DATE}`;
        myAxios.post('添加或更新', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '提交成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = async function () {
      loading.value = true;

      let P_ID = tableDatas.filters.P_ID;
      let REPORT_DATE = tableDatas.filters.REPORT_DATE;
      let params = `${P_ID}\t${REPORT_DATE}`;
      myAxios.get('陈帅廷查询配送中心报工详情', params).then(async res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oritableData = [...res];


          ElMessage({
            showClose: true,
            type: 'success',
            message: '最新数据获取成功!'
          });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      // getTableDatas();
      loading.value = true;
      let params = ``;
      myAxios.get('陈帅廷查询配送中心人员等级', params).then(async res => {
        if (res instanceof Array) {
          loading.value = false;
          // tableDatas.oritableData = [...res];
          // let p_result = await myAxios.get('陈帅廷查询配送中心人员等级', '');
          tableDatas.filters.P_OPTIONS = res.map(el => {
            return {
              "value": el.P_ID,
              "label": el.NAME,
            };
          });

          // ElMessage({
          //   showClose: true,
          //   type: 'success',
          //   message: '最新数据获取成功!'
          // });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    });

    let searchKeys = [];
    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',
        REPORT_DATE: dayjs().format('YYYY/MM/DD'),
        P_ID: '',

        P_OPTIONS: [],

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60
        },
        {
          "prop": "GX_TYPE",
          "label": "工序类型",
          "align": "center"
        },
        {
          "prop": "GX_NAME",
          "label": "工序名",
          "align": "center"
        },
        {
          "prop": "VALUE",
          "label": "数量",
          "align": "center"
        },
        // {
        //   "prop": "REMARK",
        //   "label": "备注",
        //   "align": "center"
        // },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170
        // }
      ],
      oritableData: [],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let REPORT_ID = row.REPORT_ID;

        let params = `${REPORT_ID}`;
        myAxios.post('删除', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    watch([() => tableDatas.filters.REPORT_DATE, () => tableDatas.filters.P_ID], (newVal, oldVal) => {
      if (newVal[0] && newVal[1]) {
        getTableDatas();
      }
      else {
        tableDatas.oritableData = [];
      }
    });

    return {
      loading,
      buttonClick,
      dialogDatas,
      tableDatas
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

